<?php
require_once("../../../config.inc.php");
$isReloadable = false;
require_once("../../../app/_inc/include.php");
require_once("../_inc/_mbAppDomValue.php");
require_once("./_inc/attributeFunction.php");
require_once("../domn/domainFunction.php");

$errMsg = "";
$entity = "";
$attribute = "";
$description = "";
$domain = "";
$length = 0;
$decimals = 0;
$sequence = 100;
$note = "";
$phys_param = "";
$upgrade_status = 'S';
$index = 0;
$primary_key = 'N';
$default = "";
$new_domain = "";
$domLength = 0;
$domDecimals = 0;
$type = "";
$domDomain = "";

$objUser = $_SESSION[USEROBJ];
$aDataArea = $objUser->getDataArea();
$dataArea = "";
$sCondDataArea = "";
if(isset($_REQUEST["da"])){
	$dataArea = $_REQUEST["da"];
	if(!isset($aDataArea[$_REQUEST["da"]])){
		$errMsg .= _t("L'utente non &egrave; abilitato ad accedere all'area dati")." \"<b>".$_REQUEST["da"]."\"</b>";
	}
}else if(isset($_REQUEST["data_area"])){
	$dataArea = $_REQUEST["data_area"];
	if(!isset($aDataArea[$_REQUEST["data_area"]])){
		$errMsg .= _t("L'utente non &egrave; abilitato ad accedere all'area dati")." \"<b>".$_REQUEST["da"]."\"</b>";
	}
}else{
	$errMsg .= _t("area dati non definita");
}

if(isset($_REQUEST["reqtype"])){	
	if($_REQUEST["reqtype"] == "save"){
		$errMsg .= attributeUpd();
	}
	if(isset($_REQUEST["reqtype"]) && $_REQUEST["reqtype"] == "delete"){
		$errMsg .= attributeDel();
	}
	$entity = sxREQUEST("entity");
	$attribute = sxREQUEST("attribute");
	$new_attribute = sxREQUEST("new_attribute");
	$description = sxREQUEST("description");
	$note = sxREQUEST("note");
	$domain = sxREQUEST("domain");
	$length = sxREQUEST("attr_length");
	$decimals = sxREQUEST("attr_decimals");
	$sequence = sxREQUEST("sequence");
	$phys_param = sxREQUEST("phys_param");
	$upgrade_status = sxREQUEST("upgrade_status");
	$index = sxREQUEST("index");
	$primary_key = sxREQUEST("primary_key");
	$default = sxREQUEST("default");
	$new_domain = sxREQUEST("new_domain");
	$domLength = sxREQUEST("dom_length");
	$domDecimals = sxREQUEST("dom_decimals");
	$type = sxREQUEST("type");
	$domDomain = sxREQUEST("dom_domain");
}
if(isset($_REQUEST["att"]) && isset($_REQUEST["ent"])){
	$attribute = $new_attribute = $_REQUEST["att"];
	$entity = $_REQUEST["ent"];	
	$sSQL = "SELECT * FROM attribute WHERE attribute='$attribute' AND entity='$entity'";
	if($objSDAO->query($sSQL, "att", array("contOnErr"=>true))){
		if($row = $objSDAO->fetch("att")){
			$description = $row["description"];
			$domain = $row["domain"];
			$length = $row["length"];
			$decimals = $row["decimals"];
			$note = $row["note"];
			$phys_param = $row["physical_param"];
			$upgrade_status = $row["upgrade_status"];
			$index = ($row["indexed"] == "Y")?1:0;
			$primary_key = $row["primary_key"];
			$sequence = $row["sequence"];
			$default = $row["default_value"];
		}else{
			$errMsg .= "missing attribute.<br>";
		}
	}
}
if($entity == ""){
	$errMsg .= _t("entity non definita.")."<br>";
}
if($attribute == ""){
	$errMsg .= _t("attribute non definito.")."<br>";
}
//selezione domini disponibili
$sSQL = "SELECT DISTINCT d.domain FROM domain d " .
		"INNER JOIN attribute a ON a.domain = d.domain " .
		"   AND a.entity LIKE '".$dataArea."_%' OR d.frequent='Y' " .
		"ORDER BY d.domain";
$objSDAO->query($sSQL, "dom");

//output HTML
$aOpz = array("tit2"=>_t("Modifica attribute"), "isReloadable"=>false);
echo(headerHTML($aOpz));
?>
<script language="JavaScript" type="text/javascript" src="../../_jsc/form.js"></script>  
<script language="JavaScript" type="text/javascript">
	function objFrmSave(){
		try{
			var objFrm = document.getElementById("objFrm");
			var objEnt =  document.getElementById("entity");
			var objAtt =  document.getElementById("attribute");
			var objMessArea =  document.getElementById("messArea");
			var errMsg = "";
			if(objAtt.value == ""){
				errMsg += "<?php echo _t("L'attribute &egrave; obbligatorio")?><br>";
				objAtt.className = "inpt01";
				objAtt.focus();
			}else{
				objAtt.className = "inpt01";
			}
			if(objEnt.value == ""){
				errMsg += "<?php echo _t("L'entity &egrave; obbligatoria")?><br>";			
				objEnt.className = "inpt01";
				objEnt.focus();
			}else{
				objEnt.className = "inpt01";
			}
			if(errMsg == ""){
				objFrm.submit();
			}else{
				objMessArea.innerHTML = errMsg;
			}
		}catch(e){
			raiseError(e.description, "AttributeMod -> save");
		}		
	}
	
	function checkDomain(){
		try{
			var objDom = document.getElementById("domain");
			var objNewDom = document.getElementById("new_domain");
			var objDomCont = document.getElementById("dom_container");
			if(objDom.value == "ND" || objDom.value == "NDL"){
				if(objNewDom.value == "")
					objNewDom.value=objDom.value;
				objDomCont.className="show";
			}else{
				objNewDom.value="";
				objDomCont.className="hidden";
			}
		}catch(e){
			raiseError(e.description, "AttributeMod -> checkDomain");
		}
	}
	
	function openPopUpDom() {
		try{
			var objDom = document.getElementById("domain");
			var objNewDom = document.getElementById("new_domain");
			var objDomCont = document.getElementById("dom_container");
			objNewDom.value="";
			objDomCont.className="hidden";
			window.open('domAttrPopUp.php?<?="da=$dataArea&xsn=".XSN?>','domAttrPopUp','height=500,width=500,scrollbars=yes,left=250,top=80');
		}catch(e){
			raiseError(e.description, "AttributeMod -> openPopUpDom");
		}
	}
</script>
  
<?php
echo(bodyHTML($aOpz));
echo getEntityHeader($entity);
echo("<form name=\"objFrm\" id=\"objFrm\" action=\"attributeMod.php\" method=\"POST\">\n");
echo("<input type=\"hidden\" name=\"reqtype\" id=\"reqtype\" value=\"save\">\n");
echo("<input type=\"hidden\" name=\"entity\" id=\"entity\" value=\"$entity\">\n");
echo("<input type=\"hidden\" name=\"data_area\" id=\"data_area\" value=\"$dataArea\">\n");
echo("<input type=\"hidden\" name=\"new_domain\" id=\"new_domain\" value=\"$new_domain\">\n");
echo("<input type=\"hidden\" name=\"xsn\" id=\"xsn\" value=\"".XSN."\">\n");

//output comandi
$aCmd = array("ins"=>array("pag"=>"javascript:objFrmSave()",
										"title"=>_t("save"),
										"text"=>_t("save"),
										"perm"=>"M"),
					"back"=>array("pag"=>$objUser->getHistory(0,false),
										"title"=>_t("torna alla pagina precedente senza modificare l'attribute"),
										"text"=>_t("cancel"),
										"perm"=>"R")
					);
echo(commandsHTML($aCmd));	
//form inserimento dati
echo("<table class=\"tabl01\" width=\"100%\" cellpadding=\"3\" cellspacing=\"2\">\n");
echo("<tr>" .
			"<td class=\"labl01\">Name*</td>" .
			"<td class=\"text01\">" .
			"<input type=\"hidden\" name=\"attribute\" id=\"attribute\"  value=\"$attribute\">" .
			"<input class=\"inpt01\" type=\"text\" name=\"new_attribute\" id=\"new_attribute\" maxlength=\"32\" value=\"$new_attribute\" size='30'></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Description</td>" .
			"<td class=\"text01\"><input class=\"inpt01\" type=\"text\" name=\"description\" id=\"description\" maxlength=\"80\" size=\"80\" value=\"".sxHE($description)."\"></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Domain</td>" .
			"<td class=\"text01\">");
echo("<select class=\"inpt01\" name=\"domain\" id=\"domain\" onChange=\"checkDomain()\">");
echo("<option value=\"\">----</option>");
while($row = $objSDAO->fetch("dom")){
	$chk = "";
	if($row["domain"] == $domain)
		$chk = "SELECTED";
	echo("<option value=\"".$row["domain"]."\" $chk>".$row["domain"]."</option>");
}
$chkND = "";
$chkNDL = "";
if($domain == "ND")
	$chkND = "SELECTED";
if($domain == "NDL")
	$chkNDL = "SELECTED";
echo("<option value=\"ND\" style='font-style:italic;' $chkND>-- new domain</option>");
echo("<option value=\"NDL\" style='font-style:italic;' $chkNDL>-- new lookup domain</i></option>");
echo("</select>");
echo("&nbsp;&nbsp;&nbsp;<span class='link01' onClick='javascript:openPopUpDom();'>altri domini</span>");
//dokmain type
if($domain == "ND" || $domain == "NDL"){
	$class = "show";
}else{
	$class = "hidden";
}
echo("<div class=\"$class\" id=\"dom_container\">");

echo(""._t("dominio")."&nbsp;<input class=\"inpt01\" type=\"text\" name=\"dom_domain\" id=\"dom_domain\" value=\"$domDomain\">");
echo("&nbsp;&nbsp;"._t("tipo")."&nbsp;");
echo("<select class=\"inpt01\" name=\"type\" id=\"type\">");
echo("<option value=\"\">  -----  </option>");
foreach($aDomainType as $sType=>$sTypeDescr){
	$chk = "";
	if($sTypeDescr == $type)
		$chk = "SELECTED";
	echo("<option value=\"$sTypeDescr\" $chk>$sTypeDescr</option>");
}
echo("</select>");
//lungthg and decimals
echo("&nbsp;&nbsp;Length&nbsp;<input class=\"inpt01\" type=\"text\" name=\"dom_length\" id=\"dom_length\" value=\"$domLength\">");
echo("&nbsp;&nbsp;Decimals&nbsp;<input class=\"inpt01\" type=\"text\" name=\"dom_decimals\" id=\"dom_decimals\" value=\"$domDecimals\">");
echo("</div>");
echo("</td></tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Default</td>" .
			"<td class=\"text01\"><input class=\"inpt01\" type=\"text\" name=\"default\" id=\"default\" maxlength=\"80\" size=\"80\" value=\"".sxHE($default)."\"></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Length</td>" .
			"<td class=\"text01\"><input class=\"inpt01\" type=\"text\" name=\"attr_length\" id=\"attr_length\" value=\"$length\"></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Decimals</td>" .
			"<td class=\"text01\"><input class=\"inpt01\" type=\"text\" name=\"attr_decimals\" id=\"attr_decimals\" value=\"$decimals\"></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Sequence</td>" .
			"<td class=\"text01\"><input class=\"inpt01\" type=\"text\" name=\"sequence\" id=\"sequence\" value=\"$sequence\"></td>" .
		"</tr>\n");
$aVal = getUpgradeStatusVal();
echo("<tr>" .
			"<td class=\"labl01\">Upgrade status</td>" .
			"<td class=\"text01\">".getHTMLRadio('upgrade_status', $upgrade_status, $aVal)."</td>" .
		"</tr>\n");
$chk = "";
echo("<tr>" .
			"<td class=\"labl01\">Primary key</td>" .
			"<td class=\"text01\">\n");
foreach($aPriKey as $pk => $des) {
	echo "  <input type='radio' class=\"text01\" name=\"primary_key\" id=\"primary_key\" value='$pk' ".
		(($primary_key==$pk)?'CHECKED':'').">$des&nbsp;&nbsp;&nbsp;\n";
}
echo("</td>" .
		"</tr>\n");
$chk = "";
if($index)
	 $chk = "CHECKED";
echo("<tr>" .
			"<td class=\"labl01\">Indexed</td>" .
			"<td class=\"text01\"><input class=\"text01\" type=\"checkbox\" name=\"index\" id=\"index\" $chk></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Physical parameters</td>" .
			"<td class=\"text01\"><textarea class=\"inpt01\" name=\"phys_param\" id=\"phys_param\" cols=\"80\" rows=\"3\">".sxHE($phys_param)."</textarea></td>" .
		"</tr>\n");
echo("<tr>" .
			"<td class=\"labl01\">Note</td>" .
			"<td class=\"text01\"><textarea class=\"inpt01\" name=\"note\" id=\"note\" cols=\"80\" rows=\"3\">".sxHE($note)."</textarea></td>" .
		"</tr>\n");
echo("</form>");
echo("</table>");
echo(commandsHTML($aCmd));
echo(footerHTML());

function attributeUpd(){
	global $objSDAO;
	$errMsg = "";
	$_REQUEST["new_attribute"] = strtolower(trim($_REQUEST["new_attribute"]));
	if(ereg("[^a-z0-9_]",sxREQUEST("new_attribute")))
		$errMsg .= _t("name - a-z0-9 _ allowed").".<br>";
	if(sxREQUEST("new_attribute") == "")
		$errMsg .= _t("missing name")."<br>";
		
	if(sxREQUEST("sequence") == "" )
		$_REQUEST["sequence"] = "0";
	if(ereg("[^0-9_]",sxREQUEST("sequence")))
		$errMsg .= _t("sequence not numeric")."<br>";
		
	if(sxREQUEST("attr_length") == "" )
		$_REQUEST["attr_length"] = "0";
	if(ereg("[^0-9_]",sxREQUEST("attr_length")))
		$errMsg .= _t("length not numeric")."<br>";
		
	if(sxREQUEST("attr_decimals") == "" )
		$_REQUEST["attr_decimals"] = "0";
	if(ereg("[^0-9_]",sxREQUEST("attr_decimals")))
		$errMsg .= _t("decimals not numeric")."<br>";
	
	if ((0+sxREQUEST("attr_decimals")) > (0+sxREQUEST("attr_length"))) {
		$errMsg .= _t("decimals greater than length")."<br>";
	}
	if($errMsg != ""){return $errMsg;}
	//check domain existence
	$description = sxREQUEST('description');
	if(isset($_REQUEST["new_domain"]) && $_REQUEST["new_domain"] != ""){
		$_REQUEST["domain"] = $_REQUEST["dom_domain"];
		$_REQUEST["description"] = $_REQUEST["attribute"];
		$_REQUEST["length"] = $_REQUEST["dom_length"];
		$_REQUEST["decimal"] = $_REQUEST["dom_decimals"];
		$_REQUEST["enumerable"] = "N";
		$_REQUEST["lkp_entity"] = "";
		$_REQUEST["lkp_attribute"] = "";
		if($_REQUEST["new_domain"] == "NDL"){
			$_REQUEST["lkp_entity"] = $_REQUEST["entity"];
			$_REQUEST["lkp_attribute"] = $_REQUEST["attribute"];
			$_REQUEST["enumerable"] = "E";
		}
		$_REQUEST["note"] = "";
		$_REQUEST["frequent"] = "N";
		$errMsg .= domainIns("NOREDIR");
	}
	if($errMsg != ""){return $errMsg;}
	//check length not defined in domain
	$sSQL = "SELECT d.* FROM domain d " .
				"	WHERE d.domain = '".sxRAS("domain")."'";
	$objSDAO->query($sSQL,"test");
	if ($row = $objSDAO->fetch("test")) {
		if (strpos("string,variable-string,number",$row['type'])===false) {
			if($row["length"] != 0)
				$errMsg .=_t("no length for type '%s'",$row['type'])."<br>";			
		} else {
			if (sxREQUEST("attr_length")== 0) {
				if($row["length"] == 0)
					$errMsg .=_t("missing length")."<br>";
			} else {
				if($row["length"] != 0)
					$errMsg .=_t("no length allowed")."<br>";
			}
		}
		if ($row['type']!='number') {
			if(sxREQUEST("attr_decimals") != 0)
				$errMsg .=_t("type = '%s' - decimals allowed for type 'number' only",$row['type'])."<br>";
		}			
	} else {
		$errMsg .=_t("domain not found")."<br>";
	}
	//check 1 pk autoincrement
	if (sxREQUEST('primary_key')=='X') {
		$sSQL = "SELECT count(*) as num FROM attribute " .
					"	WHERE entity = '".sxRAS("entity").
					"' AND attribute <> '".sxRAS("attribute").
					"' AND primary_key <> 'N'";
		$numEntity = 0;
		$objSDAO->query($sSQL,"test");
		$row = $objSDAO->fetch("test");
		if($row["num"] != 0)
			$errMsg .=_t("primary-key autoincr not unique")."<br>";
	}
	//check 1 pk autoincrement
	if (sxREQUEST('primary_key')=='Y') {
		$sSQL = "SELECT count(*) as num FROM attribute " .
					"	WHERE entity = '".sxRAS("entity").
					"' AND attribute <> '".sxRAS("attribute").
					"' AND primary_key = 'X'";
		$numEntity = 0;
		$objSDAO->query($sSQL,"test");
		$row = $objSDAO->fetch("test");
		if($row["num"] != 0)
			$errMsg .=_t("primary-key autoincr not unique")."<br>";
	}
	
	if($errMsg != ""){return $errMsg;}
	
	
	//check existence
	if ($_REQUEST["new_attribute"] != $_REQUEST["attribute"]) {
		$sSQL = "SELECT count(*) as num FROM attribute " .
				" WHERE entity = '".$_REQUEST["entity"]."' " .
				" AND attribute = '".$_REQUEST["new_attribute"]."'";
		$objSDAO->query($sSQL,"test");
		$row = $objSDAO->fetch("test");
		if($row["num"] != 0)
			$errMsg .= _t("existing atttribute");
	}
	
	if($errMsg != "")
		return $errMsg;
	
	$upgrade_status = sxREQUEST("upgrade_status");
	$index = (isset($_REQUEST["index"]))?"Y":"N";
	$primary_key = $_REQUEST["primary_key"];
	$length = ($_REQUEST["attr_length"] == "")?0:$_REQUEST["attr_length"];
	$decimals = ($_REQUEST["attr_decimals"] == "")?0:$_REQUEST["attr_decimals"];
	$sequence = ($_REQUEST["sequence"] == "")?0:$_REQUEST["sequence"];
	$sSQL = "UPDATE " .
			"attribute SET length=".$length.", " .
			"decimals=".$decimals.", " .
			"sequence=".$sequence.", " .
			"domain='".sxRAS("domain")."', " .
			"default_value='".sxRAS("default")."', " .
			"upgrade_status='".$upgrade_status."', " .
			"indexed='".$index."', " .
			"primary_key='".$primary_key."', " .
			"physical_param='".sxRAS("phys_param")."', " .
			"description='".sxAS($description)."', " .
			"note='".sxRAS("note")."' " .
			"WHERE attribute='".sxRAS("attribute")."' AND entity='".sxRAS("entity")."'";	
	$objSDAO->exec($sSQL);
	if ($_REQUEST["new_attribute"] != $_REQUEST["attribute"]) {
		$sSQL = "UPDATE attribute SET attribute = '".$_REQUEST["new_attribute"]."'" .
			" WHERE attribute = '".$_REQUEST["attribute"]."' AND entity = '".$_REQUEST["entity"]."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE relationship_key SET parent_attribute = '".$_REQUEST["new_attribute"]."'" .
			" WHERE parent_attribute = '".$_REQUEST["attribute"]."' AND parent_entity = '".$_REQUEST["entity"]."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE relationship_key SET child_attribute = '".$_REQUEST["new_attribute"]."'" .
			" WHERE child_attribute = '".$_REQUEST["attribute"]."' AND child_entity = '".$_REQUEST["entity"]."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE domain SET lookup_attribute = '".$_REQUEST["new_attribute"]."'" .
			" WHERE lookup_attribute = '".$_REQUEST["attribute"]."' AND lookup_entity = '".$_REQUEST["entity"]."'";	
		$objSDAO->query($sSQL,"upd");
		$sSQL = "UPDATE subtyping SET discriminating_attribute = '".$_REQUEST["new_attribute"]."'" .
			" WHERE discriminating_attribute = '".$_REQUEST["attribute"]."' AND supertype_entity = '".$_REQUEST["entity"]."'";	
		$objSDAO->query($sSQL,"upd");
	}
	$url = $_SESSION[USEROBJ]->getHistory(0, true);
	serverRedir($url);
	exit();
}
